import {Base64} from 'js-base64'

const uriKey = 'data'

const objToUri = obj => {
    if (obj) {
        const objStr = JSON.stringify(obj)
        return uriKey + '=' + Base64.utob(objStr)
    }
}

const resolveToUrl = (path, data) => {
    if (data) {
        return path + '?' + objToUri(data)
    } else {
        return path
    }
}

const optionsToObj = options => {
    if (options[uriKey]) {
        const objStr = Base64.btou(options[uriKey])
        return JSON.parse(objStr)
    }
    return {}
}

const paramsKey = '$params'

export default {
    _reLaunch(path, data) {
        uni.reLaunch({
            url: resolveToUrl(path, data)
        }).catch()
    },
    _switchTab(path, data) {
        uni.switchTab({
            url: resolveToUrl(path, data)
        }).catch()
    },
    
    get current() {
        const pages = getCurrentPages()
        return pages[pages.length - 1]
    },
    
    open(path, data) {
        uni.navigateTo({
            url: resolveToUrl(path, data),
            fail: () => this._switchTab(path, data)
        })
    },
    
    back(delta = 1) {
        uni.navigateBack({
            delta
        }).catch()
    },
    
    replace(url, data) {
        uni.redirectTo({
            url: resolveToUrl(url, data),
            fail: () => this._switchTab(url, data)
        })
    },
    
    onLoad(callback) {
        const current = this.current
        if (current[paramsKey] == null) {
            current[paramsKey] = reactive({})
        }
        onLoad(options => {
            const obj = optionsToObj(options)
            Object.assign(current[paramsKey], obj)
            callback && callback(obj)
        })
    },
    get params() {
        if (this.current[paramsKey] == null) {
            this.current[paramsKey] = reactive({})
        }
        return this.current[paramsKey]
    },
    login(unauthorized) {
        const current = this.current
        if (current.route === 'pages/my/login/index') {
            return
        }
        if (unauthorized) {
            this.$auth = this.current
        } else {
            delete this.$auth
        }
        return uni.reLaunch({
            url: '/pages/my/login/index'
        })
    },
    home(login) {
        uni.reLaunch({
            url: '/pages/tabBar/home/index',
            complete: () => {
                const next = this.$auth
                delete this.$auth
                if (login && next) {
                    this.open(next.$page.fullPath)
                }
            }
        })
    },
    
}
